package com.ruoyi.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.domain.Article;
import com.ruoyi.domain.RiverNews;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.Toutiao;
import com.ruoyi.service.IToutiaoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * toutiaoController
 * 
 * @author ya
 * @date 2025-06-23
 */
@RestController
@RequestMapping("/toutiao/toutiao")
public class ToutiaoController extends BaseController
{
    @Autowired
    private IToutiaoService toutiaoService;

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    /**
     * 自己新增river_news
     */
    //PreAuthorize("@ss.hasPermi('river_news:river_news:add')")
    @Log(title = "toutiao", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestParam(value="title",required = false) String title,
                          @RequestParam(value = "articleOrigin",required = false) String articleOrigin,
                          @RequestParam(value = "coverPath",required = false) MultipartFile coverPath,
                          @RequestParam(value ="columnId",required = false) Long columnId,
                          @RequestParam(value = "content",required = false) String content,
                          @RequestParam(value = "author",required = false) String author,
                          @RequestParam(value = "remark",required = false) String remark,
                          @RequestParam(value = "littleTitle1",required = false) String littleTitle1,
                          @RequestParam(value = "littleTitle2",required = false) String littleTitle2
                          )
    {
        Toutiao toutiao = new Toutiao();
        toutiao.setTitle(title);
        toutiao.setArticleOrigin(articleOrigin);
        toutiao.setColumnId(columnId);
        toutiao.setContent(content);
        toutiao.setAuthor(author);
        toutiao.setRemark(remark);
        toutiao.setLittleTitle1(littleTitle1);
        toutiao.setLittleTitle2(littleTitle2);
        // 处理文件上传
        if (coverPath != null && !coverPath.isEmpty()) {
            String basePath = "articleFilePath/";
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
                    + "/" + coverPath.getOriginalFilename();

            FileInfo fileInfo = fileStorageService.of(coverPath)
                    .setPath(objectName)
                    .upload();
            toutiao.setCoverPath(fileInfo.getUrl());
        }
        return toAjax(toutiaoService.insertToutiaoOwn(toutiao));
    }

    /**
     * 自己修改river_news
     */
    //@PreAuthorize("@ss.hasPermi('river_news:river_news:edit')")
    @Log(title = "toutiao", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@RequestParam("id") Long id, @RequestParam(value="title",required = false) String title,
                           @RequestParam(value = "articleOrigin",required = false) String articleOrigin,
                           @RequestParam(value = "coverPath",required = false) MultipartFile coverPath,
                           @RequestParam(value ="columnId",required = false) Long columnId,
                           @RequestParam(value = "content",required = false) String content,
                           @RequestParam(value = "author",required = false) String author,
                           @RequestParam(value = "remark",required = false) String remark,
                           @RequestParam(value = "littleTitle1",required = false) String littleTitle1,
                           @RequestParam(value = "littleTitle2",required = false) String littleTitle2
                           )
    {
        Toutiao toutiao = new Toutiao();
        toutiao.setId(id);
        toutiao.setTitle(title);
        toutiao.setArticleOrigin(articleOrigin);
        toutiao.setColumnId(columnId);
        toutiao.setContent(content);
        toutiao.setAuthor(author);
        toutiao.setRemark(remark);
        toutiao.setLittleTitle1(littleTitle1);
        toutiao.setLittleTitle2(littleTitle2);
        // 处理文件上传
        if (coverPath != null && !coverPath.isEmpty()) {
            String basePath = "articleFilePath/";
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
                    + "/" + coverPath.getOriginalFilename();

            FileInfo fileInfo = fileStorageService.of(coverPath)
                    .setPath(objectName)
                    .upload();
            toutiao.setCoverPath(fileInfo.getUrl());
        }
        return toAjax(toutiaoService.updateToutiaoOwn(toutiao));
    }

    /**
     * 查询toutiao列表
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('toutiao:toutiao:list')")
    @GetMapping("/list")
    public TableDataInfo list(Toutiao toutiao)
    {
        startPage();
        List<Toutiao> list = toutiaoService.selectToutiaoList(toutiao);
        return getDataTable(list);
    }

    /**
     * 导出toutiao列表
     */
    @PreAuthorize("@ss.hasPermi('toutiao:toutiao:export')")
    @Log(title = "toutiao", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Toutiao toutiao)
    {
        List<Toutiao> list = toutiaoService.selectToutiaoList(toutiao);
        ExcelUtil<Toutiao> util = new ExcelUtil<Toutiao>(Toutiao.class);
        util.exportExcel(response, list, "toutiao数据");
    }

    /**
     * 获取toutiao详细信息
     */
    @PreAuthorize("@ss.hasPermi('toutiao:toutiao:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(toutiaoService.selectToutiaoById(id));
    }

    /**
     * 新增toutiao
     */
    @PreAuthorize("@ss.hasPermi('toutiao:toutiao:add')")
    @Log(title = "toutiao", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Toutiao toutiao)
    {
        return toAjax(toutiaoService.insertToutiao(toutiao));
    }

    /**
     * 修改toutiao
     */
    @PreAuthorize("@ss.hasPermi('toutiao:toutiao:edit')")
    @Log(title = "toutiao", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Toutiao toutiao)
    {
        return toAjax(toutiaoService.updateToutiao(toutiao));
    }

    /**
     * 删除toutiao
     */
    @PreAuthorize("@ss.hasPermi('toutiao:toutiao:remove')")
    @Log(title = "toutiao", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(toutiaoService.deleteToutiaoByIds(ids));
    }


    /**
     * 附件上传
     */
    @Anonymous
    @PostMapping("/attachment/{id}")
    public AjaxResult uploadAttachment(@PathVariable Long id, @RequestParam MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "touTioaPath/attachment/";

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传文件，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 先查询完整的Article对象
            Toutiao toutiao = toutiaoService.getById(id);
            if (toutiao != null) {
                // 更新attachment字段
                toutiao.setAttachment(fileInfo.getUrl());
                // 更新数据库中的attachment字段
                toutiaoService.updateById(toutiao);
            }
            System.out.println("文章附件："+fileInfo.getUrl());

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


}
